package cn.stylefeng.guns.modular.demo.excel.listener.aslikang;

import cn.stylefeng.guns.core.exception.BusinessException;
import cn.stylefeng.guns.core.exception.BusinessExceptionEnum;
import cn.stylefeng.guns.dao.IGoodsService;
import cn.stylefeng.guns.dao.ISaleStockService;
import cn.stylefeng.guns.dao.ISupplierService;
import cn.stylefeng.guns.dao.entity.GaiaBatchInfo;
import cn.stylefeng.guns.dao.entity.Goods;
import cn.stylefeng.guns.dao.entity.SaleStock;
import cn.stylefeng.guns.dao.entity.Supplier;
import cn.stylefeng.guns.dao.service.IGaiaBatchInfoService;
import cn.stylefeng.guns.modular.demo.excel.domain.asilikang.ASStocakExcelVO;
import cn.stylefeng.guns.modular.demo.excel.domain.asilikang.AsSaleExcelVO;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 阿斯利康销售数据
 */
@Slf4j
public class StockAsSaleListener implements ReadListener<AsSaleExcelVO> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    private List<SaleStock> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private List<String> keyList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private ISaleStockService saleStockService;

    private List<String> errorList;
    private ISupplierService supplierService;
    private IGoodsService goodsService;
    private IGaiaBatchInfoService gaiaBatchInfoService;
    private String tag;

    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param saleStockService
     */
    public StockAsSaleListener(ISaleStockService saleStockService, ISupplierService supplierService, IGoodsService goodsService, List<String> errorList, IGaiaBatchInfoService gaiaBatchInfoService, String tag) {
        this.saleStockService = saleStockService;
        this.errorList = errorList;
        this.supplierService = supplierService;
        this.goodsService = goodsService;
        this.gaiaBatchInfoService = gaiaBatchInfoService;
        this.tag = tag;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. It is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(AsSaleExcelVO data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        String commodityName = data.getCommodityName();
        String batch = data.getBatch();
        String storeCode = data.getStoreCode();
        Integer num = data.getNum();
        String key = commodityName + batch;
//        if (keyList.contains(key)) {
//            throw new BusinessException(BusinessExceptionEnum.BUSINESS_DATA_REPEAT, "同一批次内有相同的商品 批次号:" + batch + ",商品名称:" + commodityName);
//        }

        Goods goods = goodsService.getOne(Wrappers.<Goods>lambdaQuery().eq(Goods::getCommodityCode, commodityName));
        if (Objects.isNull(goods)) {
            throw new BusinessException(BusinessExceptionEnum.BUSINESS_DATA_REPEAT, "商品不存在：" + commodityName);
        }
        List<GaiaBatchInfo> list = gaiaBatchInfoService.list(Wrappers.<GaiaBatchInfo>lambdaQuery().eq(GaiaBatchInfo::getBatBatch, batch));
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException(BusinessExceptionEnum.BUSINESS_DATA_REPEAT, "批次号不存在：" + batch);
        }
        GaiaBatchInfo gaiaBatchInfo = list.get(0);
        String batSupplierCode = gaiaBatchInfo.getBatSupplierCode();
        Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery().eq(Supplier::getSupplierCode, batSupplierCode));
        if (Objects.isNull(supplier)) {
            throw new BusinessException(BusinessExceptionEnum.BUSINESS_DATA_REPEAT, "供应商不存在：" + supplier.getSupplierCode());
        }


        SaleStock saleStock = new SaleStock();
        Date saleTime = data.getSaleTime();
        if (Objects.nonNull(saleTime)) {
            saleStock.setSaleTime(saleTime.getTime());
        }
        saleStock.setGoodsId(goods.getGoodsId());
        saleStock.setSupplierId(supplier.getSupplierId());
        saleStock.setBatchNo(data.getBatch());
        saleStock.setTest(1);
        saleStock.setBillNo(data.getBillNo());
        if (num >= 0) {
            saleStock.setSaleType(2);
        } else {
            saleStock.setSaleType(1);
        }
        saleStock.setNum(data.getNum());
        saleStock.setCanRebate(0);
        saleStock.setStoCode(storeCode);
        saleStock.setType("store");
        saleStock.setTag(tag);
        cachedDataList.add(saleStock);
//        keyList.add(key);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
//            keyList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        log.error("解析失败，但是继续解析下一行:{}", exception.getMessage());
        // 如果是某一个单元格的转换异常 能获取到具体行号
        // 如果要获取头的信息 配合invokeHeadMap使用
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            log.error("第{}行，第{}列解析异常，数据为:{}", excelDataConvertException.getRowIndex(), excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
            errorList.add("第" + excelDataConvertException.getRowIndex() + "行，第" + excelDataConvertException.getColumnIndex() + "列解析异常，数据为:" + excelDataConvertException.getCellData());
        }

        if (exception instanceof BusinessException) {
            errorList.add(exception.getMessage());
        }

    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        saleStockService.saveBatch(cachedDataList);
        log.info("存储数据库成功！");
    }

}
